package com.czy.booktest02.demos.interceptor;

import com.czy.booktest02.demos.common.redis.CacheService;
import com.czy.booktest02.demos.common.redis.RedisKey;
import com.czy.booktest02.demos.pojo.bo.AccountUserBo;
import com.czy.booktest02.demos.utils.AppJwtUtil;
import com.czy.booktest02.demos.utils.BaseUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@Component
public class GlobalInterceptor implements HandlerInterceptor {

    @Autowired
    private CacheService cacheService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果是登录或者注册则放行
        String token = request.getHeader("token");
        Map<String, String[]> parameterMap = request.getParameterMap();
        request.getParameterMap().forEach((key,value)->{
            System.out.println("key"+key);
            System.out.println("value"+value);
        });
        System.out.println(request.getRequestURL());


        //判断token是否为空
        if(Strings.isBlank(token))
            return shareModule("token为空!");
        //解析token
        //判断token是否过期
        try{
            //可能解析失败,所以try一下(别try啊,如果你要try那你就别try啊)
            Claims claims = AppJwtUtil.getClaimsBody(token);
            //-1,0表示有效,1或2表示无效
            int i = AppJwtUtil.verifyToken(claims);
            int id =  Integer.parseInt((String) claims.get("id"));
            Map<String, Object> parameterMaps = BaseUtils.secondMapPutIntoFirstMap(
                    BaseUtils.quickCreateMap("userId", id)
                    , cacheService.getMap(RedisKey.USER_INFORMATION + id)
            );
            if(parameterMaps==null||i==1||i==2){
                return shareModule("token已经过期,请重新登录!");
            }
            AccountUserBo accountUserBo = BaseUtils.mapToObjectConverter(parameterMaps, AccountUserBo.class);
            if(accountUserBo==null){
                return shareModule("用户未登录!");
            }
            //如果为0,则禁用
            if(accountUserBo.getUserId()==0){
                return shareModule("该账户被禁用!");
            }
            return AccountUserBo.saveUser(accountUserBo);
        }catch (Exception e){
            e.printStackTrace();
            return shareModule("token解析失败");
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AccountUserBo.clear();
    }

    private boolean shareModule(String msg) {
        log.info(msg);
        return false;
    }
}
